﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace PwjCy.Lite.Common
{
    /// <summary>
    /// HashCache缓存
    /// </summary>
    public sealed class LocalCacheHelper
    {
        private Cache _LocalCache
        {
            get { return HttpRuntime.Cache; }
        }
        private const string CacheKeyPrefix = "Pwjcy_Lite_LocalCacheHelper";
        private LocalCacheHelper() { }
        private static readonly Lazy<LocalCacheHelper> lazy = new Lazy<LocalCacheHelper>(() => new LocalCacheHelper());
        public static LocalCacheHelper Instance { get { return lazy.Value; } }
        /// <summary>
        /// 添加永久缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="key"></param>
        public void AddCache<T>(T obj, string key)
        {
            _LocalCache.Insert(CacheKeyPrefix + typeof(T).FullName + key, obj);
        }
        /// <summary>
        /// 添加过期缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="key"></param>
        /// <param name="expireSeconds"></param>
        public void AddCache<T>(T obj, string key, int expireSeconds)
        {
            _LocalCache.Insert(CacheKeyPrefix + typeof(T).FullName + key, obj, null, DateTime.Now.AddSeconds(expireSeconds), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetCache<T>(string key)
        {
            return (T)_LocalCache.Get(CacheKeyPrefix + typeof(T).FullName + key);
        }
        /// <summary>
        /// 添加缓存依赖
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="key"></param>
        /// <param name="dep">依赖键</param>
        public void AddCacheDependency<T>(T obj, string key, System.Web.Caching.CacheDependency dep)
        {
            _LocalCache.Insert(CacheKeyPrefix + typeof(T).FullName + key, obj, dep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
    }
}
